package com.example.security;

import cn.hutool.json.JSONUtil;
import com.example.common.lang.Result;
import com.example.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理器
 */

@Component                      //作用：用于把当前类对象存入spring容器中
public class LoginSuccessHandler implements AuthenticationSuccessHandler {  //继承security的登录成功处理器

    @Autowired
    JwtUtils jwtUtils;                                              //把JwtUtils注入ioc容器

    //security的登录成功处理器重写
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {


        response.setContentType("application/json;charset=UTF-8");  //返回数据为json格式，utf-8编码
        ServletOutputStream outputStream = response.getOutputStream();  //生成输出流准备用输出流的方式flush推出

        //生成JWT,并放置到请求头中
        String jwt = jwtUtils.generateToken(authentication.getName());  //调用jwtUtils工具类生成一个jwt
        response.setHeader(jwtUtils.getHeader(),jwt);                   //设置请求头中jwt名称和jwt的值

        Result result = Result.succ("????");              //成功返回的结果

        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));    //把Result序列化成json的字节码utf-8格式

        outputStream.flush();       //把流推出
        outputStream.close();       //释放资源

    }
}
